package com.vedio.service;

import com.vedio.dao.UserDao;
import com.vedio.entity.User;
import com.vedio.mapper.UserMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class UserService implements UserDao {
    String resource = "mybatis-config.xml";
    InputStream inputStream = Resources.getResourceAsStream(resource);
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    //2.获取SqlSessionFactory对象，用它执行sql语句
    SqlSession sqlSession = sqlSessionFactory.openSession(true);
    //3.执行sql
    //List<Product> products = sqlSession.selectList("test.selectAll");
    //获取mapper接口的代理对象
    UserMapper userMapper = sqlSession.getMapper(UserMapper.class);

    public UserService() throws IOException {
    }

    @Override
    public List<User> selectAll() throws IOException {

        List<User> users = userMapper.selectAll();
        //释放资源
        sqlSession.close();
        return users;
    }

    @Override
    public User selectById(Integer id) {
        User user = userMapper.selectById(id);
        sqlSession.close();
        return user;
    }

    @Override
    public int add(User user) {
        int result = userMapper.add(user);
        sqlSession.close();
        return result;
    }

    @Override
    public int update(User user) {
        int result = userMapper.update(user);
        sqlSession.close();
        return result;
    }

    @Override
    public int deleteById(Integer id) {
        int result = userMapper.deleteById(id);
        return result;
    }
}
